package com.uinnova.product.eam.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Iterator;
import java.util.List;

/**
 * 全局的跨域配置
 *
 *
 * @author yuhao.guan
 * @version 2020/8/7
 */

@Configuration
public class GlobalCorsConfig {

    @Value("#{'${uino.eam.allowed.origins}'.split(',')}")
    private List<String> allowOrigins;

    @Bean
    public CorsFilter corsFilter() {
        Iterator<String> iterator = allowOrigins.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if(next == null || "".equals(next.trim())){
                iterator.remove();
            }
        }
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(allowOrigins);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("Content-Disposition");
        //if (!allowOrigins.contains("*")) {
            config.setAllowCredentials(true);
        //}

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configSource);
    }
}